package bookManage.model;

import java.io.Serializable;
import java.util.UUID;

import bookManage.util.BookUtil;

public class BookModel implements Comparable<BookModel>, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Integer id;// 图书id
	private String isbn;// 图书isbn码
	private String name;// 图书名
	private int num;// 图书的借阅次数

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		if (search(id, null)) {// true没有重复
			this.id = id;
			return;
		}
		// 有重复
		System.out.print("图书id重复，已为您自动生成一个id：");
		this.id = (int) (Math.random() * 2000000000 + 0);
		System.out.println(this.id);
	}

	public String getIsbn() {
		return isbn;
	}

	public void setIsbn(String isbn) {
		if (search(null, isbn)) {
			this.isbn = isbn;
			return;
		}
		System.out.print("图书ISBN码重复，已为您自动生成一个ISBN码：");
		this.isbn = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10);
		System.out.println(this.isbn);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getNum() {
		return num;
	}

	public void setNum() {
		this.num = this.num + 1;
	}

	@Override
	public String toString() {
		return "BookModel [id=" + id + ", isbn=" + isbn + ", name=" + name + ", num=" + num + "]";
	}

	/**
	 * 找有无重复的id或者isbn
	 * 
	 * @param id
	 * @param isbn
	 * @return
	 */
	public boolean search(Integer id, String isbn) {
		if (id != null) {
			for (BookModel book : BookUtil.books) {
				if (book.id.equals(id)) {
					return false;// false 说明有重复id
				}
			}
		}

		if (isbn != null) {
			for (BookModel book : BookUtil.books) {
				if (book.isbn.equals(isbn)) {
					return false;// false 说明有重复isbn
				}
			}
		}

		return true;// true 遍历一遍未找到重复id和isbn
	}

	@Override
	public int compareTo(BookModel o) {
		int num = o.num - this.num;// 设置按借阅次数降序排列
		int num2 = num == 0 ? this.name.compareTo(o.isbn) : num;// 借阅次数和isbn都一致算同一种书

		return num2;
	}

}
